﻿#include "CSVTool.h"
#include <QFile>
#include "Logger.h"
#include <stdexcept>
bool CSVTool::WriteCSV(const QVector<QString>& header, const QVector<QString>& keyValuePair, const char* codec)
{
    QFile file(m_fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)) {
        Logger::GetInstance().LogError("Failed to open file for writing");
        return false;
    }
    QTextStream outFile(&file);
    outFile.setCodec(codec);
    try {
        outFile << header[0] << ": " << header[1];
        outFile << "\n";
        for (const QString& item : keyValuePair) {
            QStringList parts = item.split(" : ");
            if (parts.size() != 2) {
                Logger::GetInstance().LogError("Data item format is invalid");
                throw std::runtime_error("Data item format is invalid");
            }
            outFile << parts[0] << " : " << parts[1];
            outFile << "\n";
        }
    }
    catch (const std::exception& ex) {
        Logger::GetInstance().LogError(QString("Error while writing csv:") + ex.what());
        file.close();
        return false;
    }
    file.close();
    return true;
}

QVector<QString> CSVTool::readCSV()
{
    QVector<QString>data;
    QFile file(m_fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        Logger::GetInstance().LogError("Failed to open file for reading");
        return data;
    }
    QTextStream in(&file);
    in.setCodec("UTF-8");
    QString headerLine = in.readLine();
    while (!in.atEnd()) {
        QString dataLine = in.readLine();
        data.append(dataLine);
    }
    file.close();
    return data;

}
